﻿@{
    ViewBag.Title = "Index";
    Layout = "~/Areas/Admin/Views/Shared/_LayoutList.cshtml";
}
<div id="liebiao"></div>
<div class="admin-main">

    <style type="text/css">
        .boderRed{
           border: 1px solid red;
       }
        /*.layui-layer{
               position: absolute;
                top: 0 !important;
                left: 0 !important;
                right: 0;
                bottom: 0;
                margin: auto;
        }*/
       /*
           .layui-table-fixed-scroll:hover{
            overflow-y:hidden !important;
        }
        .layui-table-body:hover{
            overflow-y:hidden !important;
        }
       */ 
        #pic1{ width: 100%; height: 100%; max-height: 300px;max-width: 300px; border-radius: 5px; -webkit-box-shadow: 5px 5px 5px 5px hsla(0,0%,5%,1.00); box-shadow: 5px 5px 5px 0px hsla(0,0%,5%,0.3); } 
/*2020-07-28*/
	    .ul_incr li{
	        font-size:16px;
	        line-height:28px;
	        height: 28px;
	        cursor:pointer;
	        text-align:left;padding: 0 15px;display: inline-block;vertical-align: top;
	    }
		.ul_incr li a{word-wrap:break-word;display: inline-block;}
      .ul_incr {
            width: 100%;display: inline-block;vertical-align: top;color:#FFFFFF;index:999; border:1px solid #CCC;border-radius:5px;background: #405467;padding: 10px 5px
        }
        .tanchu{
	        color: #000;width: 100%;height: 100%;display: inline-block
        }
	</style>

    <blockquote class="layui-elem-quote p5">
        <form id="formSearch" class="layui-form" action="/Index" method="post">
            <div class="layui-form-item">
                <label class="layui-form-label">产品类目：</label>
                <div class="layui-input-inline">
                    @Html.CategoryHtml(ViewData["BaseCategory"], Request["category"])
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">商品采集：</label>
                <div class="layui-input-inline " style="width:82%">
                    <textarea placeholder="请输入1688商品详情网址(如:https://detail.1688.com/offer/616334320245.html)，多个网址用Enter换行" class="layui-textarea" rows="3" autocomplete="off" id="prodUrls"></textarea>
                </div>

                <div class="layui-input-inline" style="width:10%;margin-top:5px">
                    @Html.SearchBtnHtml("开始采集")
                    <button type="reset" class="layui-btn layui-btn-primary" style="width:115px;float:left;margin:12px 0px 0px 0px">重置</button>
                </div>
            </div>

        </form>
    </blockquote>

   
    <blockquote class="layui-elem-quote p5">
        <form id="formEdit" class="layui-form">
            <div class="layui-form-item" style="margin-bottom:0px">
                <a class="layui-btn" lay-filter="saveForm" id="saveForm" style="float:right">一键闪存</a>
                <a class="layui-btn" lay-filter="submitForm" id="moveTo" style="float:left">移入产品库</a>

                <div style="float:right;">
                    @Html.TopToolBarHtml(ViewData["ActionFormRightTop"])
                </div>
            </div>

            <table id="defaultTable" lay-filter="defaultruv"></table>
            <script type="text/html" id="bar">
                @Html.ToolBarHtml(ViewData["ActionList"])
            </script>
        </form>
    </blockquote>
    </div>
<input type="hidden" value="" id="ono">

<script type="text/javascript" src="https://www.hzcbdt.com/Areas/Admin/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="https://www.hzcbdt.com/Areas/Admin/Scripts/jquery-migrate-1.1.1.js"></script>
<script type="text/javascript" src="https://www.hzcbdt.com/Areas/Admin/Scripts/jquery.dragsort-0.5.1.min.js"></script>
<script src="http://open.web.meitu.com/sources/xiuxiu.js" type="text/javascript"></script>

<script type="text/javascript">
    layui.use(['table', 'common', 'form', 'tablePlug', 'optimizeSelectOption'], function () {
        //layui.use(['table', 'common', 'form'], function () {
        var table = layui.table,
            form = layui.form,
            common = layui.common,
            $ = layui.$;
        var selectItemDic =@Html.SelectOptionsData(ViewData["OptionsData"]);
//         var getOptions = function (field,notNull) {
//             return function (data) {
//                 var value = data[field];
//                 if (selectItemDic[field]) {
//                     //selectItemDic[field].indexOf('^')>0                  
//                     var options = [];
//                     var itemArray = selectItemDic[field].split('^');
//                     $.each(itemArray,function(idx,item){
//                         var itemVal = item.split('$');
//                         options.push('<option value="'+ itemVal[0] +'" ' + (value === itemVal[1] || itemArray.length==1 ? 'selected' : '') + '>'+itemVal[1]+'</option>');
//                         //options.push('<option value="'+ optionEnglish[idx] +'" ' + (value === item || value==optionEnglish[idx] ? 'selected' : '') + '>'+item+'</option>');
//                     });
//                     return [
//                           '<select class="options" lay-filter="city_select" '+ (notNull==1? 'lay-verify=\"required\"':'') +  'lay-search="" value="' + value + '">',
//                           '<option value="" >请选择或搜索</option>',
//                           ,options.join('')
//                           ,'</select>'
//                     ].join('');
// 
//                     //if (1==1) {
//                     //}else{
//                     //    var itemVal = selectItemDic[field].split('$');
//                     //    return  '<div><input type=\"text\" class=\"layui-input\" value=\"'+itemVal[1]+'\" /></div>';
//                     //}
//                 }
//             };
//         };

        var getOptions = function (field,notNull,o) {
            return function (data) {
                var value = data[field] ? data[field] : '<span style="color: red">请选择</span>';
                if (selectItemDic[field]) {
                    //selectItemDic[field].indexOf('^')>0                  
                    var options = [];
                    var itemArray = selectItemDic[field].split('^');
                    
                    if( itemArray.length == 1 ){
                        var itemVal = itemArray[0].split('$');
                        value=itemVal[1];
                    }
                    
                    var aaaaa = '';
                    $.each(itemArray,function(idx,item){
                        var itemVal = item.split('$');                        
                        if(value == itemVal[1]){
                            aaaaa = itemVal[0];
                        }
                    });
                }
                var ono = $("#ono").val()*1 + 1;
                $("#ono").val(ono);
                return ['<a class="v_'+field+' tanchu" id="ono_'+ono+'" issize="option_'+o+'" index="'+o+'" param="'+field+'" href="javascript:;">' + value + '</a>'].join('');
            };
        }
        var getOptions2 = function (field,index) {
            return function (data) {
                var value = data[field];
                if (selectItemDic[field]) {
                    //selectItemDic[field].indexOf('^')>0                  
                    var options = [];
                    var itemArray = selectItemDic[field].split('^');
                    $.each(itemArray,function(idx,item){
                        var itemVal = item.split('$');
                        options.push('<li><a param="'+ itemVal[0] +'">'+itemVal[1]+'</li>');
                        //options.push('<option value="'+ optionEnglish[idx] +'" ' + (value === item || value==optionEnglish[idx] ? 'selected' : '') + '>'+item+'</option>');
                    });
                    return [
                          '<div id="option_' + index + '" style="display:none;">',
                          '<ul class="ul_incr">',
                          ,options.join('')
                          ,'</ul></div>'
                    ].join('');

                    //if (1==1) {
                    //}else{
                    //    var itemVal = selectItemDic[field].split('$');
                    //    return  '<div><input type=\"text\" class=\"layui-input\" value=\"'+itemVal[1]+'\" /></div>';
                    //}
                }
            };
        };
//-_-

        form.on('select(category)', function(data){
            location.href='/datasrv/product?id=12&category='+data.value;
        });

        function setImageHover(){            
            $(".woimg img").hover(function(){
                var size = $(this)[0].naturalWidth + "X"+ $(this)[0].naturalHeight;
                $(this).parent().append("<p id='wopic'><img src='"+$(this).attr("src")+"' id='pic1'></p>");
                $(this).parent().mousemove(function(e){
                    console.log(e);
                    var top=e.pageY > 600 ? e.pageY-300:e.pageY;
                      
                    $("#wopic").css({
                        "width": "300px;",
                        "height": "300px;",
                        'position': 'fixed',
                        "top":top+"px",//(e.clientY+20)
                        "left":(e.clientX+ 20)+"px",
                        "z-index": 9999
                    }).fadeIn("fast");                       
                });
            },function(){
                $("#wopic").remove();
            });      
        }

        function showPopup(event,divId,dtop,sid,oid){
            //                    console.log();
            var wh = document.body.clientHeight*1 / 2;
            $(".showbox").hide();
            $('#'+divId).addClass("showbox");
            var left = $(event).parent().parent().offset().left
            , dheight = $('#'+divId).height();
                   
            if($(event).parent().parent().offset().top > wh){
                var top = $(event).parent().parent().offset().top - dheight*1;
            } else {
                var top = $(event).parent().parent().offset().top + dtop;
            }
            var showbox=$('#'+divId).css({
                top:top,
                left:left
            });
            if(oid){
                $('#'+divId).attr('data-oid',oid);
                $('#'+divId).attr('data-sid','');
            } else if(sid) {
                $('#'+divId).attr('data-sid',sid);
                $('#'+divId).attr('data-oid','');
            } else {
                $('#'+divId).attr('data-oid','');
                $('#'+divId).attr('data-sid','');
            }
				   
            $('#'+divId).attr("colIndex",$(event).attr("index"));
            $('#'+divId).show();
        }

        //表格
        table.render({
            id: 'defaultReload'
           , elem: '#defaultTable'
            , height: 'full-140'
            // 开启智能重载
            , smartReloadModel: true
           , url: '/DataSrv/Product/List?ProductType=1' //数据接口
           , page: true //开启分页
           , cols: [[ //表头
                       { checkbox: true, fixed: 'left',width: 35}
                      , { field: 'ImageUrl', title: '图片', width: 80, fixed: 'left', templet: '<div><div class="woimg"><a target="_blank" href="{{d.OriProductUrl}}"><img prodId="{{d.Id}}" style="width: 50px; height:50px; display: block;" src="{{d.ImageUrl}}"/></a></div></div>', align: 'center' }
                     , { field: 'SkuId', width: '5%', title: 'Sku', align: 'center' }
                      @Html.TabaleHeadHtml(ViewData["TableHead"])
                     , {  fixed: 'right',field: '', title: '操作', width: 180, toolbar: "#bar" }
           ]]
            ,done: function(res, curr, count){
                ///*参考需要循环添加*/
                $(".layui-table-header th a").each(function(index,item){
                    $("#liebiao").append(getOptions2(item.innerText,index+1));
                })
                setImageHover();

                //$(".woimg img").hover(function(){
                //    var size = $(this)[0].naturalWidth + "X"+ $(this)[0].naturalHeight;
                //    $(this).parent().append("<p id='wopic'><img src='"+$(this).attr("src")+"' id='pic1'></p>");
                //    $(this).parent().mousemove(function(e){
                //        console.log(e);
                //        var top=e.pageY > 600 ? e.pageY-300:e.pageY;
                      
                //        $("#wopic").css({
                //            "width": "300px;",
                //            "height": "300px;",
                //            'position': 'fixed',
                //            "top":top+"px",//(e.clientY+20)
                //            "left":(e.clientX+ 20)+"px",
                //            "z-index": 9999
                //        }).fadeIn("fast");

                //        //var father = document.getElementById('formEdit').clientHeight
                //        //if(father - e.pageY  + 180> 300) {
                //        //    $("#wopic").css({
                //        //        "width": "300px;",
                //        //        "height": "300px;",
                //        //        'position': 'fixed',
                //        //        "top":(e.clientY+20)+"px",//(e.clientY+20)
                //        //        "left":(e.clientX+ 20)+"px",
                //        //        "z-index": 9999
                //        //    }).fadeIn("fast");
                //        //}else{
                //        //    $("#wopic").css({
                //        //        "width": "300px;",
                //        //        "height": "300px;",
                //        //        'position': 'fixed',
                //        //        "bottom":(father - e.clientY - 180)+"px",//(e.clientY+20)
                //        //        "left":(e.clientX+ 20)+"px",
                //        //        "z-index": 9999
                //        //    }).fadeIn("fast");     
                //        //}
                       
                //    });

                //    //var height = $(obj).height()*3;
                //    //var width = $(obj).width()*3;
                //    //var url =  $(obj).attr("src");

                //},function(){
                //    $("#wopic").remove();
                //});                           
               
                $(".layui-table-header table .hd").each(function(idx,obj){
                    $(obj).parent().parent().hover(function(){
                        var divId = $(obj).attr('issize');
                        var sid = $(obj).text();
                        console.log(sid);
                        var showbox=$('#'+divId).css({
                            position:'absolute',
                            zIndex:999,
                            width:'240px',
                        });
                        showPopup(obj,divId,26,sid);
                    },function(){
                        //$(".showbox").hide();
                    })
                });
               
                $(".layui-table-body table .tanchu").each(function(idx,obj){
                    var divId = $(obj).attr('issize')
                    ,param = $(obj).attr('param')
                    ,oid = $(obj).attr('id');
                    var xianshi ='0';
                    $(obj).parent().parent().hover(function(){
                        var showbox=$('#'+divId).css({
                            position:'absolute',
                            zIndex:999,
                            width:'240px',
                        });
                        showPopup(obj,divId,50,param,oid);
                    },function(){});
		           
                });
                $(document).bind("click",function(e){
                    $(".showbox").hide();
                })

                $("#liebiao").find().hover(function(){
                    $(this).show();
                },function(){
                    $(this).slideUp(300).delay(800).fadeIn(400);
                });         

                $(".ul_incr a").click(function(){
                    var startVal = 0;
                    var incVal2 = $(this).attr('param');//注意：incVal2为需要写入数据库的值
                    var oid = $(this).parent().parent().parent().attr('data-oid');
                    var sid = $(this).parent().parent().parent().attr('data-sid');
                    var incVal = $(this).text();
                    if (incVal=='') return;
                    if(oid){
                        $("#"+oid).text(incVal);
                        $(".showbox").hide();
                    } else if(sid) {
                        $(".v_"+sid).each(function(){
                            $(this).text(incVal);
                        });
                        $(".showbox").hide(function(obj){
                        });
                    }
                    $("#"+oid).parent().removeClass("boderRed");                  
                });
            }
           ,where: {CategoryCode: $("#selCategoryCode").val()}
        });


        var active = {
            reload: function () {
                $('#ajax-loader').fadeOut(); //todo：加载滚动条
                //执行重载
                table.reload('defaultReload', {
                    page: {
                        curr: 1 //重新从第 1 页开始
                    }
                  , where: urlToJson(encodeURIComponent($("#formSearch").serialize()))
                });
            }
        };
        //服务器排序
        table.on('sort(defaultruv)', function (obj) {
            //尽管我们的 table 自带排序功能，但并没有请求服务端。
            //有些时候，你可能需要根据当前排序的字段，重新向服务端发送请求，如：
            table.reload('defaultReload', {
                initSort: obj //记录初始排序，如果不设的话，将无法标记表头的排序状态。 layui 2.1.1 新增参数
              , where: { //请求参数
                  field: obj.field //排序字段
                , order: obj.type //排序方式
              }
            });
        });

        $('#btnSearch').on('click', function () {
            var categoryCode = $("#selCategoryCode").val();
            if (categoryCode=='') {
                layer.alert('请先选择产品类目!',{icon: 2, time: 3000 });
                return;
            }
            var type = $(this).data('type');
            var urls = $("#prodUrls").val();
            if (urls!='') {
                layer.load(); //loading
                $.ajax({
                    url: "/DataSrv/Product/FetchItem?ProductType=1&categoryCode=" + $("#selCategoryCode").val(),
                    type: "POST",
                    data: { oriProductUrls: urls },
                    dataType: "json",
                    success: function (data) {
                        //active['reload'].call(this);
                        active[type] ? active[type].call(this) : '';
                        layer.closeAll('loading'); //关闭loading
                    }
                });
            }else{
                active[type] ? active[type].call(this) : '';
            }
        });

        $('#saveForm').on('click', function () {
            //check必填项
            if (!layui.form.checkInput($('#formEdit'))) return false;

            var productList = [];
            var productRows = $(".layui-table-main tr");
            if (productRows != null) {
                for (var i = 0; i < productRows.length; i++) {
                    var productData = { KeyAttributes: "" };
                    var selVal = $(productRows[i]).find('td select');

                    var inputs = $(productRows[i]).find('td input');

                    for (var j = 1; j < inputs.length; j++) {
                        var propVal = $(inputs[j])[0].value;
                        var endStr = j == inputs.length - 1 ? "" : "^";
                        productData.KeyAttributes += propVal + endStr;
                    }
                    productData.Id = $(productRows[i]).find('td img').attr("prodId");
                    productList.push(productData);
                }

                $.ajax({
                    url: "/Datasrv/Product/updateProductBatch?categoryCode=" + $("#selCategoryCode").val(),
                    type: "POST",
                    data: { productParam: productList },
                    dataType: "json",
                    success: function (data) {
                        if (data.state == "success") {
                            common.msgSuccess("更新成功");
                        } else {
                            common.msgError("更新失败");
                        }
                    }
                });
            }
        });

        $('#moveTo').on('click', function () {
            var cbxs =  $(".layui-table-main").find('input[type="checkbox"]');
            var rows =  $(".layui-table-main").find('tr');

            var _list = [];var isOk = true;
            cbxs.each(function (index, item) {
                if (item.checked == true) {
                    console.log(index);
                    var row = rows[index];                  
                    var inputs = $(row).find('td input');
                    var selCtrls = $(row).find('td select');
                    var prodId =  $(row).find('img').attr('prodid');
                    var  keyAttributes = getProdAttributes(selCtrls,inputs);    
                    if (keyAttributes!='') {
                        _list.push({ "Id": prodId ,"KeyAttributes":keyAttributes});      
                    }else{
                        isOk = false;
                        return;
                    }
                }                
            });
            if (isOk) {
                if (_list.length>0) {    
                    moveToProductRepository(_list);
                }else{                    
                    common.msgError("请先勾选待移入产品库的产品！");
                }
            }          
        });

        //add
        $('#btnAdd').on('click', function () {
            common.openTop({
                title: '操作添加', w: '670px', h: '500px', content: '/Datasrv/Product/Add/'
            });
        });
        //监听工具条
        table.on('tool(defaultruv)', function (obj) {
            var data = obj.data;
            switch (obj.event) {
                case "detail":
                    common.openTop({
                        detail: true,
                        title: '操作详情', w: '568px', h: '400px', content: '/Datasrv/Product/Detail/' + data.Id, clickOK: function (index) {
                            common.close(index);
                        }
                    });
                    break;
                case "del":
                    layer.confirm('确定要删除吗？', function (index) {
                        $.ajax({
                            url: "/Datasrv/Product/Delete",
                            type: "POST",
                            data: { "Id": data.Id },
                            dataType: "json",
                            success: function (data) {
                                if (data.state == "success") {
                                    layer.close(index); //关闭弹框
                                    common.msgSuccess("删除成功");

                                    active['reload'].call(this);
                                } else {
                                    common.msgError("删除失败");
                                }
                            }
                        });
                    });
                    break;
                case "edit":
                    var widthC = document.body.clientWidth 
                    var widthL = '800px' 
                    var heightC = document.body.clientHeight
                    var heightL = '400px' 
                    console.log(widthC,'widthC!!!!!!!!')
                    if(widthC > 1080){
                        widthL = '1500px'
                        heightL = '600px'
                    } 
                    if ( widthC > 2300) {
                        widthL = '1900px'
                        heightL = '1000px'
                    }
                    layer.open({
                        type: 2,
                        title: '编辑子商品',
                        area: [widthL, heightL],
                        content: '/Datasrv/SubProduct/Edit/' + data.Id +'?isEng=0',
                        //btn:['一键保存'],
                        yes: function(index, layero){
                            common.msgSuccess("save~~~");
                        }
                    });
                    break;

                case "downLoadImg":
                    window.open('/Datasrv/Product/DownImages?productId=' + data.Id, "_blank");
                    break;
                case "move":
                    var keyAttributes = ''; var chkRet = true;
                    var selectItemVals = obj.tr.find('td a');
                    for (var i = 1; i < selectItemVals.length; i++) {
                        if (selectItemVals[i].innerText=='请选择') {
                            $(selectItemVals[i]).parent().addClass("boderRed");
                            chkRet=false;
                        }
                        var endStr = i == selectItemVals.length - 1 ? "" : "^";
                        keyAttributes += selectItemVals[i].innerText + endStr;
                    }

                    if (!chkRet) {
                        layer.alert('请先完成红框属性值设置！</br>(注意:拖动页面底部横向滚动条，即可看到完整属性)',{icon: 2, time: 100000 });
                        return;
                    }
                    //var inputs = obj.tr.find('td input');
                    //var selCtrls = obj.tr.find('td select');

                    //keyAttributes= getProdAttributes(selCtrls,inputs);
                    if (keyAttributes!='') {
                        var _list =[{ "Id": data.Id ,"KeyAttributes":keyAttributes}];
                        moveToProductRepository(_list);
                    }
                  
                    break;
                default:

            }
        });

        //单行属性值
        function  getProdAttributes(selCtrls,inputs){
            var attributes = '';var chkRet =true;var left = 0;
            for (var j = 0; j < selCtrls.length; j++) {
                var propVal = selCtrls[j].value;
                var notNull = 'required' == $(selCtrls[j]).attr('lay-verify');
                if (notNull && propVal == '') {
                    $(inputs[j+1]).parent().addClass("boderRed");
                    layer.alert('请先完成红框属性值设置！</br>(注意:拖动页面底部横向滚动条，即可看到完整属性)',{icon: 2, time: 10000 });
                    //common.msgError("请先完成各属性值设置！</br>(左右拖动表格底部滚动条，可以看到完整属性)");
                    if (left==0) {
                        left = $(inputs[j+1]).offset().left- 300;
                    }                 
                 
                    //$(".layui-table-box").stop().animate({scrollLeft:left},500);

                    chkRet  =false;                   
                }
                var endStr = j == inputs.length - 1 ? "" : "^";
                attributes += propVal + endStr;
            }
            if (!chkRet) {
                attributes = ''
                $(".layui-table-main").scrollLeft(left);
            }
           
            return attributes;
        }

        function  moveToProductRepository(attributeList){
            layer.load(); //loading
            $.ajax({
                url: "/Datasrv/Product/MoveTo",
                type: "POST",
                data: {"prodAttibutes":attributeList},
                dataType: "json",
                success: function (data) {
                    layer.closeAll('loading'); //关闭loading
                    if (data.state == "success") {
                        common.msgSuccess("移入成功");
                        setTimeout(function () {
                            active['reload'].call(this);
                        }, 1200);
                    } else {
                        layer.alert(data.message,{icon: 2, time: 10000 });
                        //common.msgError(data.message);
                    }
                }
            });
        }

    });
</script>


